package com.esdk.sql;

import java.io.Serializable;
import java.sql.Connection;
import java.util.*;
import java.util.stream.Collectors;

import com.esdk.esdk;
import com.esdk.sql.orm.IRow;
import com.esdk.sql.orm.ParentRow;
import com.esdk.sql.orm.RowUtils;
import com.esdk.utils.EasyArray;
import com.esdk.utils.EasyStr;

public class MysqlDialect extends SqlDialect{

	public MysqlDialect(){
		super(ConnMetaData.DatabaseProductName_MySQL,null,null);
	}

	public MysqlDialect(String databaseProductName,String databaseProdcutVersion,Integer databaseMajorVersion){
		super(databaseProductName,databaseProdcutVersion,databaseMajorVersion);
	}

	public MysqlDialect(Connection conn){
		super(conn);
	}

  @Override public StringBuilder getSQL(Columns columns,Froms froms,Wheres wheres,String distinct,int offset
			,int limit,OrderBys orderbys,GroupBys groupbys){
  	if(limit>0){
    	StringBuilder stmtSql=join("SELECT",distinct,columns.assemble(),froms.assemble(),wheres.assemble()
    			,groupbys.assemble(),orderbys.assemble(),limit>0?"LIMIT ".concat(String.valueOf(limit)):""
    			,offset>=0?"OFFSET ".concat(String.valueOf(offset)):"");
			return stmtSql;
		}else
			return super.getSQL(columns,froms,wheres,distinct,offset,limit,orderbys,groupbys);
	}

	/**
	 * 处理转义符\，把\变成\\，把'变成''，把$变成\$
	 * */
	@Override
	public String adjustStmtSQLValue(String sql){
		return sql.replace("'","''").replace("\\","\\\\").replaceAll("\\$","\\\\\\$");
	}

	@Override
	public StringBuilder parse(Columns columns,Froms froms,Wheres wheres,String distinct,int offset,int limit,
			OrderBys orderbys,GroupBys groupbys){
		if(limit>0){
			StringBuilder pstmtSql=join("SELECT",distinct,columns.assemble(),froms.assemble(),wheres.getPstmtSql()
					,groupbys.assemble(),orderbys.assemble(),limit>0?"LIMIT ".concat(String.valueOf(limit)):""
					,offset>0?"OFFSET ".concat(String.valueOf(offset)):"");
			return pstmtSql;
		}else
			return super.parse(columns,froms,wheres,distinct,offset,limit,orderbys,groupbys);
	}
	
	@Override
	public StringBuilder parseBatchReplace(String tableName,List<IRow> prs,boolean ignoreRowChanged){
		ArrayList<Object[]> values=new ArrayList(prs.size());
		for(IRow row:prs){
			if(ignoreRowChanged || row.isChanged()){
				if(row instanceof ParentRow){
					ParentRow parentRow=(ParentRow)row;
					if(parentRow.getPKID()==null && !parentRow.isAutoIncrement())
						parentRow.setPKID(RowUtils.genNextPrimaryId());
					parentRow.fillCommonFields();
				}
				List result=row.toList();
				values.add(result.toArray());
			}
		}
		StringBuilder sb=new StringBuilder().append("Replace Into ");
		sb.append(parseValues(tableName,prs.get(0).getColumns(),values));
		return sb;
	}
}
